package com.baosight.sczx.common.zm;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.resource.Resources;
import com.baosight.iplat4j.core.spring.SpringApplicationContext;
import com.baosight.iplat4j.core.sqldao.impl.NamedSqlDaoSpringJdbcImpl;
import com.baosight.iplat4j.dao.Dao;
import com.baosight.iplat4j.ep.DaoEPBase;

public class Utils {
	
	public static final String QUERY_CONDITION_BLOCK_ID = "inqu_status";
	public static final String RESULT_BLOCK_ID = "result";
	public static final String RESULT_BLOCK_ATTR_COUNT = "count";
	public static String TEMP_FILE = "eedm.tempfile.dir";
	public static int EIInfoServiceStatusFaild = -1;
	
	@SuppressWarnings("rawtypes")
	public static void setMsgBySearchResult(EiInfo info, String blockName) {
		Map attr = info.getBlock(blockName).getAttr();
		if(attr!=null)
		{
			
			if(info.getBlock(blockName).get(Utils.RESULT_BLOCK_ATTR_COUNT)!=null)
			{
				String count = info.getBlock(blockName).get(Utils.RESULT_BLOCK_ATTR_COUNT).toString();
				info.setMsg("查询成功，本次查询返回"+count+"条记录！");
			}
		}
	}
	

	/**
	 * 取得文件上传路径
	 * @return
	 */
	public static String getEEDMTempFileDir() {

		//SoaConfig soaConfig = (SoaConfig) SpringApplicationContext.getBean(SoaConstants.SOACONFIG);
		//String templateDir = soaConfig.getServiceProperty(TEMP_FILE);
		String templateDir = Resources.getValue("message", TEMP_FILE);

		if (templateDir == null)
			templateDir = "";

		return templateDir;
	}

	/**
	 * 取得所要生成的block数据块
	 * @param id
	 * @param bean
	 * @param sql
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unused" })
	public static EiBlock generateBlock(String id, DaoEPBase bean, String sql) {
		EiBlock block = new EiBlock(id);
		Dao dao = (Dao)SpringApplicationContext.getBean("dao");
		block.setBlockMeta(bean.eiMetadata);
		
		int offset = 0;
		int limit = 1000;
		int size = 1000;
		java.util.List returnList = null;

		int totalSize = 0;

		while (size == limit)
		{
			try {
				returnList = dao.query(sql, new HashMap(),
						offset, limit);

				if (returnList != null){
					size = returnList.size();
					block.addRows(returnList);
				}
				else
					size = 0;

				offset += limit;

				totalSize += size;

			} catch (Exception ex) {
				ex.printStackTrace();
				break;
			}
		}
		return block;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked", "unused" })
	public static EiBlock generateOutBlock(String id, DaoEPBase bean, EiInfo inInfo, String sql, boolean addNewRow, String conditionBlock)
	{
		EiBlock block = new EiBlock(id);
		Dao dao = (Dao) SpringApplicationContext.getBean("dao");
		block.setBlockMeta(bean.eiMetadata);
		
		if(addNewRow)
		{
			block.addRow(bean.toMap()); //加一空行
		}
		int offset = 0;
		int limit = 1000;
		int size = 1000;
		java.util.List returnList = null;

		int totalSize = 0;
		
		HashMap conditionMap = new HashMap();	
       if(inInfo.getBlock(conditionBlock)!=null)
       {	
		 int conditionCount = inInfo.getBlock(conditionBlock).getRowCount();
		 for(int i=0; i<conditionCount; i++)
		 {
		 	conditionMap.putAll(inInfo.getBlock(conditionBlock).getRow(i));
		 }
       }
		while (size == limit) {
			try {
				returnList = dao.query(sql, conditionMap, offset, limit);

				if (returnList != null) {
					size = returnList.size();
					block.addRows(returnList);
					
				} else
					size = 0;

				offset += limit;

				totalSize += size;

			} catch (Exception ex) {
				ex.printStackTrace();
				break;
			}
		}
		return block;
	}
	public static EiBlock generateOutBlock(String id, DaoEPBase bean, EiInfo inInfo, String sql, boolean addNewRow) {
		return generateOutBlock(id, bean, inInfo, sql, addNewRow, "inqu_status");
	}
	
	public static Long generateNewKey(String keyField, String tableName) {
		
		String sql = "select max(" + keyField + ")+1 from " + tableName;
		return generateNewKey(sql);
	}

	/**
	 * 取得新的主键值
	 * @param tableName 表名
	 * @param columnName 主键的列名
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Long generateNewKey(String sql) {
		
		Dao dao = (Dao) SpringApplicationContext.getBean("dao");
		Long newId = new Long(-1);
		java.util.List returnList = null;
 
		try {
			returnList = dao.query(sql, new Long(0));
			if (returnList != null) {
				String id = returnList.get(0).toString();
				newId = Long.parseLong(id);
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		if (newId <= 0)	{
			newId = Long.parseLong("1");
		}

		return newId;
	}
	
	/**
	 * 取得新的数据库连接
	 * @return
	 */
	public static Connection getConnection() {
		NamedSqlDaoSpringJdbcImpl dao = (NamedSqlDaoSpringJdbcImpl) SpringApplicationContext
				.getBean("namedSqlDao");
		Connection con = dao.getDbConnection();
		return con;
	}
	
	/**
	 * 执行sql语句（非查询类）
	 * @return
	 */
	public static void executeSql(Connection con, String sql) throws SQLException {
		PreparedStatement stm = con.prepareStatement(sql);
		stm.execute();
		stm.close();
	}

	public static boolean hasRecord(Connection con, String sql) throws SQLException {
		PreparedStatement stm = con.prepareStatement(sql);
		ResultSet rs = stm.executeQuery();
		rs.next();
		int resultCount = rs.getInt(1);
		if (resultCount > 0) {
			return true;
		} else {
			return false;
		}
	}
	
	public static EiInfo generateAutoPageEiInfo( String blockName )
	{
		EiInfo info = new EiInfo();
		EiBlock block = info.addBlock( blockName );
		block.set( "showCount", "true" );
		block.set( "limit", "10" );
		block.set( "offset", "0" );
		
		return info;
	}
	
	/**
	 * 查询数量，当sql只返回一条int类型数据时使用
	 * @param _dao
	 * @param queryName
	 * @param params
	 * @return
	 */
	public static int queryNumber(Dao _dao, String queryName, HashMap<String, String> params) {
		List<?> result = _dao.query(queryName, params);
		int cnt = 0;
		if(result.get(0) != null)
			cnt = Integer.parseInt(result.get(0).toString());	
		return cnt;
	}
	
	/**
	 * 
	 * <p>Function: decomposeMaterialTypeWithLevel</p>
	 * <p>Description: 根据物资级别分解物资分类</p>
	 * <p>return value:List</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2012-1-17下午01:48:17 bobswang
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private static List decomposeMaterialTypeWithLevel(List inList)
	{
		List result = new ArrayList();
		List result_1 = new ArrayList();
		List result_2 = new ArrayList();
		List result_3 = new ArrayList();
		for(int i=0; i<inList.size(); i++)
		{
			Map map = (HashMap)inList.get(i);
			if("1".equals(map.get("fdTypeLevel").toString()))
			{
				result_1.add(map.get("fdAllTypeCode"));
			}
			else if("2".equals(map.get("fdTypeLevel").toString()))
			{
				result_2.add(map.get("fdAllTypeCode"));
			}
			else
			{
				result_3.add(map.get("fdAllTypeCode"));
			}
		}
		
		result.add(result_1);
		result.add(result_2);
		result.add(result_3);
		return result;
	}
	
	/**
	 * 
	 * <p>Function: generateValidateData</p>
	 * <p>Description: 生成包括1、2、3级物资分类的有权限物资分类，如3级分类有1、2级的分类编码，认为仅3级分类码有效</p>
	 * <p>return value:List</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2012-1-17下午01:48:56 bobswang
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static List generateValidateData(List inList)
	{
		List _list = decomposeMaterialTypeWithLevel(inList);
		List _list1 = (ArrayList)_list.get(0);
		List _list2 = (ArrayList)_list.get(1);
		List _list3 = (ArrayList)_list.get(2);
		List resultList = new ArrayList();
		
		for(int i=0; i<_list3.size(); i++)
		{
			resultList.add(_list3.get(i));
		}
		
		for(int i=0; i<_list2.size(); i++)
		{
			String _str2 = _list2.get(i).toString();
			boolean hasCode = false;
			for(int j=0; j<_list3.size(); j++)
			{
				String _str3 = _list3.get(j).toString();
				if(_str3.startsWith(_str2))
				{
					hasCode = true;
					break;
				}
			}
			if(!hasCode)
			{
				resultList.add(_str2);
			}
		}
		
		for(int i=0; i<_list1.size(); i++)
		{
			String _str1 = _list1.get(i).toString();
			boolean hasCode1 = false;
			boolean hasCode2 = false;
			for(int j=0; j<_list3.size(); j++)
			{
				String _str3 = _list3.get(j).toString();
				if(_str3.startsWith(_str1))
				{
					hasCode1 = true;
					break;
				}
			}
			
			for(int k=0; k<_list2.size(); k++)
			{
				String _str2 = _list2.get(k).toString();
				if(_str2.startsWith(_str1))
				{
					hasCode2 = true;
					break;
				}
			}
			
			if(!hasCode1 && !hasCode2)
			{
				resultList.add(_str1);
			}
		}
		
		return resultList;
	}
}

